<?php
namespace App\V3\V3_2_7\Services;

use App\Services\CloudPrinterService;
use App\V3\V3_2_7\Models\CloudDeviceModel;
use App\Services\CommonService;
use App\V3\V3_2_7\Models\CloudDevicePrinterJobModel;
use App\V3\V3_2_7\Models\CloudDevicePrinterModel;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use function EasyWeChat\Kernel\Support\str_random;

class CloudService
{
    //打印任务参数配置
    public static $_PRINTER_CONFIG = [
        'jobFile'       => '',//文件绝对路径
        'dmPaperSize'   => 9,//9=A4，11=A5
        'dmOrientation' => 1,//1=坚向，2=横向
        'dmCopies'      => 1,//打印份数，最多100份
        'callbackUrl'   =>'',//云服务回调url
    ];

    /**
     * 保存source为文件，
     * 报表打印前，可以先生成 excel ，word ，png文件，再调用打印接口
     * @return string 返回保存文件的绝对路径
     */
    public static function storeSourceFile($fileSource,$fileType='png')
    {
        $fileName       = str_random(20).'_'.date("YmdHis").'_'.mt_rand(1000,9999);
        $fileDir        = 'printer'.date("/Ymd/");
        $fileNameFull   = $fileName.'.'.$fileType;
        Storage::put($fileDir.$fileNameFull,$fileSource);
        $fullPath       = public_path().'/uploads/'.$fileDir.$fileNameFull;
        return $fullPath;
    }

    /**
     * 添加云盒设备
     */
    public static function deviceAdd($mainId,$data)
    {
        //先判断是否存在
        $deviceModel    = CloudDeviceModel::query()->where('main_id',$mainId)
                                                   ->where('device_id',$data['device_id'])
                                                   ->first();

        if(!empty($deviceModel)){
            return CommonService::fail('设备已存在，不能重复添加！');
        }

        //实例模型
        $deviceModel    = new CloudDeviceModel();
        if(!empty($data['device_name'])){
            $deviceModel->device_name       = $data['device_name'];
        }
        $deviceModel->main_id               = $mainId;
        $deviceModel->device_id             = $data['device_id'];
        $deviceModel->device_pwd            = $data['device_pwd'];
        $deviceModel->device_action_status  = '';
        $deviceModel->device_expired_at     = 0;
        $deviceModel->device_status         = CloudDeviceModel::$_DEVICE_STATUS_2;//待审核
        $deviceModel->device_is_delete      = 2;//1=删除，2=未删除
        $deviceModel->save();

        return CommonService::success('添加成功',['cd_id'=>$deviceModel->cd_id]);
    }

    /**
     * 编辑设备，如有变动，需要重新审核状态
     */
    public static function deviceEdit($mainId,$data)
    {
        //先判断是否存在
        $deviceModel    = CloudDeviceModel::query()->where('cd_id',$data['cd_id'])
                                                   ->where('main_id',$mainId)
                                                   ->first();

        if(empty($deviceModel)){
            return CommonService::fail('数据不存在！');
        }
        if(isset($data['device_name'])){
            $deviceModel->device_name       = $data['device_name'];
        }
        //编辑数据
        $deviceModel->device_id     = $data['device_id'];
        $deviceModel->device_pwd    = $data['device_pwd'];

        //如果数据有变动，就重置数据为 “待审核” 状态
        if($deviceModel->isDirty()){
            $deviceModel->device_status = CloudDeviceModel::$_DEVICE_STATUS_2;//待审核
        }

        $flag = $deviceModel->save();

        if($flag){
            return CommonService::success('编辑成功');
        }else{
            return CommonService::fail('编辑失败');
        }

    }

    /**
     * 删除设备
     */
    public static function deviceDel($mainId,$data)
    {
        //先判断是否存在
        $deviceModel    = CloudDeviceModel::query()->where('cd_id',$data['cd_id'])
                                                    ->where('main_id',$mainId)
                                                    ->first();

        if(empty($deviceModel)){
            return CommonService::fail('数据不存在！');
        }

        //编辑数据
        $deviceModel->device_is_delete     = 1;// 1=删除，2=正常
        $flag = $deviceModel->save();

        if($flag){
            return CommonService::success('删除成功');
        }else{
            return CommonService::fail('删除失败');
        }

    }

    /**
     * 获取云盒信息
     */
    public static function deviceInfo($mainId,$deviceId)
    {
        //先判断是否存在
        $deviceModel    = CloudDeviceModel::query()->where('main_id',$mainId)
            ->where('device_id',$deviceId)
            ->first();

        return $deviceModel;
    }

    /**
     * 设备列表
     */
    public static function deviceList($mainId,$data)
    {
        $query      = CloudDeviceModel::query();

        $query->where('main_id',$mainId);
        if($data['device_id'] != ''){
            $query->where('device_id',$data['device_id']);
        }

        $modelList  = $query->paginate($data['pageSize'],['*'], '',$data['currentPage']);

        return $modelList;
    }

    /**
     * 云盒打印机列表
     */
    public static function devicePrinterList($mainId,$deviceId)
    {
        $query      = CloudDevicePrinterModel::query();

        $query->where('main_id',$mainId);
        $query->where('device_id',$deviceId);

        $modelList  = $query->get();

        return $modelList;
    }


    /**
     * 设备状态同步，并同步打印机信息
     */
    public static function deviceSync($mainId,$deviceId)
    {
        //先判断是否存在
        $deviceModel    = CloudDeviceModel::query()->where('device_id',$deviceId)
                                                   ->where('main_id',$mainId)
                                                   ->first();

        if(empty($deviceModel)){
            return CommonService::fail('数据不存在！');
        }
        //是否已经审核
        if($deviceModel->isCheckPass() == false){
            return CommonService::fail('设备待审核！');
        }

        //实例“链科”接口
        //new CloudPrinter("API Key", '设备ID', '设备密码', true);
        $apiKey     = Config('app.lianke_cloud_api_key');
        $devicePwd  = $deviceModel->device_pwd;
        $cloudPrinterService    = new CloudPrinterService($apiKey,$deviceId,$devicePwd,false);
        try{
            $cloudPrinterService->asyncRefreshDeviceInfo();//先刷新设备信息
            $deviceInfo = $cloudPrinterService->getDeviceInfo();
        }
        catch(Exception $e) {
            return CommonService::fail($e->getMessage());
        }

        //更新设备状态
        $objInfo = $deviceInfo->info;

        if($objInfo->online == 1){
            //设备在线
            $deviceModel->device_action_status = 'up';
        }else{
            $deviceModel->device_action_status = 'down';
        }
        $deviceModel->save();

        //更新打印机列表信息
        $printerList = $cloudPrinterService->getPrinterList();

        if(!empty($printerList))
        {
            $usbList        = [];//自动删除不存在的打印机
            $queryPrinter   = CloudDevicePrinterModel::query();

            foreach ($printerList as $pk => $printer)
            {
                array_push($usbList,$printer->port);

                $curPrinter = $queryPrinter->where('main_id',$mainId)
                             ->where('cd_id',$deviceModel->cd_id)
                             ->where('cdp_port',$printer->port)
                             ->first();

                if(!empty($curPrinter)){
                    //已经存在，更新就行了
                    $curPrinter->cdp_driver_type    = $printer->driver_type;
                    $curPrinter->cdp_printer_name   = $printer->drivce_name;
                    $curPrinter->cdp_driver_name    = $printer->driver_name;
                    $curPrinter->cdp_is_printer     = $printer->isPrinter;
                    $curPrinter->cdp_port           = $printer->port;
                    $curPrinter->cdp_support_status = $printer->support_status;
                    $curPrinter->cdp_printer_species= $printer->species;

                }else{
                    //未存在，写入新数据
                    $curPrinter = new CloudDevicePrinterModel();

                    $curPrinter->main_id            = $mainId;
                    $curPrinter->cd_id              = $deviceModel->cd_id;
                    $curPrinter->device_id          = $deviceId;
                    $curPrinter->cdp_driver_type    = $printer->driver_type;
                    $curPrinter->cdp_printer_name   = $printer->drivce_name;
                    $curPrinter->cdp_driver_name    = $printer->driver_name;
                    $curPrinter->cdp_is_printer     = $printer->isPrinter;
                    $curPrinter->cdp_port           = $printer->port;
                    $curPrinter->cdp_support_status = $printer->support_status;
                    $curPrinter->cdp_printer_species= $printer->species;
                    $curPrinter->cdp_action_status  = 'bind';

                }

                $curPrinter->save();

            }//foreach

            //删除当前云盒下不存在的打印机
            CloudDevicePrinterModel::query()->where('main_id',$mainId)
                                            ->where('cd_id',$deviceModel->cd_id)
                                            ->whereNotIn('cdp_port',$usbList)
                                            ->delete();

        }

        return CommonService::success("更新云盒状态为 {$deviceModel->device_action_status} 状态。");
    }


    /**
     * 审核云盒状态
     */
    public static function deviceCheckAdmin($data)
    {
        $mainId         = $data['main_id'];
        $deviceId       = $data['device_id'];
        $deviceStatus   = $data['device_status'];

        //先判断是否存在
        $deviceModel    = CloudDeviceModel::query()->where('device_id',$deviceId)
                                                    ->where('main_id',$mainId)
                                                    ->first();

        if(empty($deviceModel)){
            return CommonService::fail('数据不存在！');
        }

        $deviceModel->device_status = $deviceStatus;
        $flag = $deviceModel->save();

        if($flag){
            $statusMsg = CloudDeviceModel::$_DEVICE_STATUS_LIST[$deviceStatus];
            return CommonService::success("审核状态为 '{$statusMsg}'");
        }else{
            return CommonService::fail('审核失败');
        }

    }

    /**
     * 设备列表（管理员）
     */
    public static function deviceListAdmin($data)
    {
        $query      = CloudDeviceModel::query();
        if($data['device_id'] != ''){
            $query->where('device_id',$data['device_id']);
        }

        $modelList  = $query->paginate($data['pageSize'],['*'], '',$data['currentPage']);

        return $modelList;
    }


    /**
     * 公共方法，任何地方，统一调用此处，添加打印任务
     * @param $mainId 主帐号id
     * @param $deviceId 云盒设备id 字符串
     * @param $cdpPort 打印机端口
     */
    public static function printerJobAdd($mainId,$deviceId,$cdpPort,$config)
    {
        //参数验证，带条件搜索
        $validator = Validator::make($config, [
            'jobFile'       =>'required|string|between:1,500',//文件绝对路径
            'dmPaperSize'   =>'required|integer|in:9,11',//9=A4，11=A5
            'dmOrientation' =>'required|integer|in:1,2',//1=坚向，2=横向
            'dmCopies'      =>'required|string|between:1,100',//打印份数，最多100份
            'callbackUrl'   =>'between:0,100', //云打印回调函数，可以通过打印任务状态
        ],[
            'jobFile.required'          => '文件绝对路径`jobFile`丢失',
            'dmPaperSize.required'      => '纸张类型`dmPaperSize`丢失',
            'dmOrientation.required'    => '横竖方向`dmOrientation`丢失',
            'dmCopies.required'         => '打印份数`dmCopies`丢失',
        ]);

        //先判断是否存在
        $deviceModel    = CloudDeviceModel::query()->where('device_id',$deviceId)
            ->where('main_id',$mainId)
            ->first();

        if(empty($deviceModel)){
            return CommonService::fail('云盒不存在！');
        }

        //是否已经审核
        if($deviceModel->isCheckPass() == false){
            return CommonService::fail('云盒待审核！');
        }

        if($deviceModel->isOnLine() == false){
            return CommonService::fail('云盒不在线！');
        }

        //验证打印机
        $printerModel   = CloudDevicePrinterModel::query()->where('cdp_port',$cdpPort)
                                                          ->where('main_id',$mainId)
                                                          ->where('device_id',$deviceId)
                                                          ->first();

        if(empty($printerModel)){
            return CommonService::fail('打印机不存在！');
        }

        if($printerModel->isValid() == false){
            return CommonService::fail('当前打印机不可用！');
        }

        DB::beginTransaction();
        try {

            //添加到云打印机任务上，添加成功后，删除本地生成的临时文件
            //实例“链科”接口
            //new CloudPrinter("API Key", '设备ID', '设备密码', true);
            $apiKey = Config('app.lianke_cloud_api_key');
            $devicePwd = $deviceModel->device_pwd;
            $cloudPrinterService = new CloudPrinterService($apiKey, $deviceId, $devicePwd, false);

            //查询打印结果
            /*
            $task_id = '80125669-ae36-4e19-8a2d-9acb3729fba1';
            $device_port = 1;
            print_r($cloudPrinterService->getJobStatus($device_port, $task_id));
            exit;
            */


            //提交打印任务
            $jobFilePath = $config['jobFile'];
            $task = $cloudPrinterService->addJob($printerModel->cdp_port, $printerModel->cdp_driver_name, $config['dmPaperSize'], new \CURLFile($jobFilePath));

            if (!empty($task)) {

                //删除文件
                @unlink($jobFilePath);

                $printerModel->cdp_printer_times += 1;
                $printerModel->cdp_printer_times_money += $printerModel->jobMoney();
                $printerModel->save();

                //写入任务表
                $jobModel = new CloudDevicePrinterJobModel();
                $jobModel->main_id      = $mainId;
                $jobModel->cdp_port     = $cdpPort;
                $jobModel->device_id    = $deviceId;
                $jobModel->cdpj_task_id = $task->task_id;
                $jobModel->cdpj_body_formdata   = json_encode($config);
                $jobModel->cdpj_money           = $printerModel->jobMoney();
                $jobModel->cdpj_submit_status   = 1; //1=任务提交成功，2=提交失败;
                $jobModel->cdjp_callback_status = 0; //1=打印成功，2=打印失败;
                $jobModel->cdjp_callback_log    = '';
                $jobModel->save();

            }

            DB::commit();
        }
        catch(\Exception $e) {
            DB::rollBack();
            return CommonService::fail($e->getMessage());
        }

        return CommonService::success('添加打印任务成功');

    }

    /**
     * 打印任务列表
     */
    public static function printerJobList($mainId,$data)
    {
        $query      = CloudDevicePrinterJobModel::query();

        $query->where('main_id',$mainId);
        if($data['device_id'] != ''){
            $query->where('device_id',$data['device_id']);
        }

        $modelList  = $query->paginate($data['pageSize'],['*'], '',$data['currentPage']);

        return $modelList;
    }

    /**
     * 打印任务删除
     */
    public static function printerJobDel($mainId,$data)
    {
        $query      = CloudDevicePrinterJobModel::query();

        $delNum       = $query->where('main_id',$mainId)
                            ->where('cdpj_id',$data['cdpj_id'])
                            ->delete();

        return CommonService::success("删除 {$delNum} 条");
    }

    /**
     * 打印任务详情
     */
    public static function printerJobDetail($mainId,$data)
    {
        $query      = CloudDevicePrinterJobModel::query();

        $jobModel   = $query->where('main_id',$mainId)
                            ->where('cdpj_id',$data['cdpj_id'])
                            ->first();

        return $jobModel;
    }

    /**
     * 打印配置参数
     */
    public static function printerConfig($mainId)
    {
        //查询所有设备，打印机
        $deviceModelList    = CloudDeviceModel::query()->where('main_id',$mainId)
            ->where('device_status',1)
            ->where('device_action_status','up')
            ->get();

        if(empty($deviceModelList)){
            return CommonService::fail('正常云盒数据为空！');
        }
        $deviceIdList   = Arr::pluck($deviceModelList,'device_id');

        //查看所有打印机
        $printerModelList   = CloudDevicePrinterModel::query()->whereIn('device_id',$deviceIdList)
                                                              ->where('main_id',$mainId)
                                                              ->where('cdp_action_status','bind')
                                                              ->where('cdp_driver_type',1)
                                                              ->get();

        if(empty($printerModelList)){
            return CommonService::fail('打印机数据为空！');
        }

        //封装成固定结果格式
        $config     = [];
        foreach ($deviceModelList->toArray() as $device)
        {
            $curPrinterList = [];
            foreach ($printerModelList->toArray() as $printer){
                if($printer['device_id'] == $device['device_id']){
                    array_push($curPrinterList,$printer);
                }
            }

            $device['printerList']      = $curPrinterList;

            array_push($config,$device);
        }


        return $config;
    }

}
